/*
   Copyright 2011 Jason Drake (jadrake75@gmail.com)
 
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.javad.components;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;

import org.jdesktop.swingx.action.OpenBrowserAction;

@SuppressWarnings("serial")
public class LinkLabel extends JLabel {

	
	private static final String A_HREF = "<a href=\""; 
	private static final String HREF_CLOSED = "\">"; 
	private static final String HREF_END = "</a>";
	
	public LinkLabel() {
		this("");
	}
	
	public LinkLabel(String text) {
		if (UIHelper.isBrowsingSupported()) {
			 setCursor(new Cursor(Cursor.HAND_CURSOR)); 
			 addMouseListener(new LinkMouseListener()); 
		}
	}
	
	@Override
	public void setText(String text) { 
		super.setText( (UIHelper.isBrowsingSupported() ? UIHelper.convertToMultiline(generateAsLink(text)) : text));
	}
	
	private class LinkMouseListener extends MouseAdapter { 
		private long clickTime = 0;
		
	    @Override 
	    public void mouseClicked(MouseEvent evt) { 
	        JLabel l = (JLabel) evt.getSource(); 
	        if( evt.getWhen() - clickTime < 2000) {
	        	return;
	        }
	        OpenBrowserAction browser = new OpenBrowserAction(convertToPlainText(l.getText()));
	        browser.actionPerformed(new ActionEvent(l, evt.getID(), Desktop.Action.BROWSE.toString()));
	        clickTime = evt.getWhen();
	    } 
	} 

	/**
	 * Convert a html HREF to the plain text URL.
	 * 
	 * @param s
	 * @return
	 */
	protected String convertToPlainText(String s) { 
	    return s.substring(s.indexOf(A_HREF) + A_HREF.length(), s.indexOf(HREF_CLOSED)); 
	} 
	
	/**
	 * Create a html HREF from a string.
	 * 
	 * @return
	 */
	protected String generateAsLink(String s) { 
	    return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END); 
	} 
	
}
